package gptliaotiantest;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ClientNetworkHandler {
    private Socket socket;
    private PrintWriter out;
    private SwingChatClient chatClient;

    public ClientNetworkHandler(SwingChatClient chatClient,String host,int port,String name) throws IOException {
        this.chatClient = chatClient;
        try {
            socket = new Socket(host, port); // 服务器地址和端口
            System.out.println(socket.isConnected());
            out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8"), true);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( socket.getInputStream(),"UTF-8"));

            out.println(name);
            // 启动一个单独的线程来处理从服务器接收的消息
            Thread receiveThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            System.out.println("readLine");
                            String msg = bufferedReader.readLine();
                            if(msg==null){
                                chatClient.exit();
                                break;
                            }
                            if("evet".equals(msg)){
                                continue;
                            }
                            System.out.println(msg);
                            chatClient.appendMessage(msg);
                        } catch (IOException e) {
                            e.printStackTrace();
                            chatClient.exit();
                            break;
                        }
                    }
                }
            });
            receiveThread.start();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }

    public void sendMessage(String message) {
        chatClient.appendMessage(message);
        out.println(message);
    }
}
